package io.persimmon.core.module.calculation;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.stream.Stream;

@Slf4j
@SuppressWarnings("unchecked")
public class CalculationTask<D> {
    private List<Calculation> calculationList = new ArrayList<>();

    public static <D> CalculationTask<D> create() {
        return new CalculationTask<D>();
    }

    public CalculationTask<D> accept(D data) {
        this.calculationList.forEach(c -> {
            c.accept(data);
        });
        return this;
    }

    public CalculationTask<D> accept(Collection<D> data) {
        data.forEach(this::accept);
        return this;
    }

    public CalculationTask<D> accept(Stream<D> data) {
        data.forEach(this::accept);
        return this;
    }

    public CalculationTask<D> addCalculation(List<Calculation> calculationList) {
        this.calculationList.addAll(calculationList);
        return this;
    }

    public void resultToConsumer() {
        this.calculationList.forEach(c -> {
            Object o = c.calculationResult();
            Consumer consumer = c.getResultConsumer();
            if (Objects.nonNull(consumer)) {
                consumer.accept(o);
            }
        });

    }
}
